package com.yunjing.elasticjob.job;

import com.cxytiandi.elasticjob.annotation.ElasticJobConf;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.yunjing.elasticjob.elastic.MyElasticJob;
import com.yunjing.elasticjob.entity.JobConfig;
import com.yunjing.elasticjob.entity.JobConfigRepository;
import com.yunjing.elasticjob.service.ElasticJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author zhiqi.shao
 * @Date 2018/6/12 17:37
 */
@Slf4j
@ElasticJobConf(name = "SimpleJob1", cron = "0/10 * * * * ?", eventTraceRdbDataSource = "datasource")
public class SimpleJob1 implements SimpleJob {

    @Autowired
    private JobConfigRepository jobConfigRepository;


    @Autowired
    private ElasticJobService elasticJobService;

    /**
     * 执行分片任务
     *
     * @param context 分片信息上下文
     */
    @Override
    public void execute(ShardingContext context) {
        List<JobConfig> allJobConfigs = jobConfigRepository.findInitJobConfig(0);
        if (allJobConfigs == null || allJobConfigs.isEmpty()) {
            return;
        }

        allJobConfigs.forEach(jobConfig -> {
            //if (jobConfig.getId() % context.getShardingTotalCount() == context.getShardingItem()) {
                log.info("SimpleJob1 Sharding:{} accept   and  will addJob ", context.getShardingItem());
                if (elasticJobService.addJob(jobConfig, MyElasticJob.class,
                        context.getShardingTotalCount())) {
                    jobConfigRepository.updateOverdueById(jobConfig.getId());
                }
           // }
        });
    }


}
